<?php

namespace app\api\service;

use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;

class Team extends Controller {

    /**
     * 获取门店首頁数据
     * @param $param
     * @return array
     */
    public static function get_team_index_info($param) {
        try {
            $member = model('member')->get(['id' => $param['member_id']]);
            $erweima_text = request()->domain() . url('common/team_scan_code', ['parent_openid' => $member->openid,'parent_id' => $member->id]);

            // 处理路径
            $root_path = ROOT_PATH . 'public' . DS;
            $upload_path = 'uploads' . DS . 'distribution' . DS;
            $file_name = time() . '_' . $member->id . '.png';
            $dir = $root_path . $upload_path;
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }

            $wx_qr_code = $root_path . $member->wx_qr_code;
            if (!$member->wx_qr_code || !is_file($wx_qr_code)) {
                // 二维码不存在 生成二维码
                Loader::import('QRcode.phpqrcode');

                $erweima_image = $upload_path . $file_name; // 出库二维码地址
                $erweima_url = $root_path . $erweima_image;

                \QRcode::png($erweima_text, $erweima_url, '', 6, 2); // 生成二维码

                $logo = $headimgurl = $member->memberRoleInfo->headimgurl;
                if (preg_match('/^((https|http)?:\/\/)[^\s]+/i', $headimgurl)) // 有图片检查是否有域名
                {
                    // 有就先保存到本地
                    $logo = $root_path . 'uploads' . DS . 'headimgurl' . DS;
                    getImage($headimgurl, $logo, $member->id . '.png');
                    $logo .= $member->id . '.png';
                }
                erweima_add_logo($erweima_url, $logo); // 添加logo

                model('member')->save(['wx_qr_code' => $erweima_image], ['id' => $member->id]);
                $member->wx_qr_code = $erweima_image;
            }

            // 一级团队人数
            $ids = model('member')->where('parent_id', $param['member_id'])->column('id');
            $team_two = $team_one = count($ids);

            // 二级团队人数
            if ($team_one > 0) {
                $team_two = model('member')->where('parent_id', 'in', $ids)->count();
            }

            $data = [
                'team_one' => $team_one,
                'team_two' => $team_two,
                'mobile' => $member->username,
                'wx_qr_code' => get_img_url($member->wx_qr_code),
                'erweima_text' => $erweima_text,
                'image' => PUBLIC_URL . 'static/home/images/logo.png'
            ];

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }
}
